/**
 * @author Steve Sedlmayr
 * @mail ssedlmayr@gmail.com
 * @link http://code.google.com/p/chitin/
 * @version 0.1
 
	The MIT License

	Copyright (c) 2009 Steve Sedlmayr

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

package srs.chitin 
{	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.system.ApplicationDomain;
	
	import mx.events.ModuleEvent;
	import mx.modules.IModuleInfo;
	import mx.modules.ModuleManager;
	
	import srs.chitin.data.LocalDataDelegate;
	import srs.chitin.data.SharedStateDelegate;
	import srs.chitin.module.extensible.InboundEvent;
	import srs.chitin.module.extensible.OutboundEvent;
	import srs.chitin.mvstate.base.ViewBase;
	import srs.chitin.mvstate.extensible.View;
	import srs.chitin.util.implementation.vo.VOUtil;
    
	public class ModuleDelegateView extends View {
		private static var _instance:ModuleDelegateView;
		
		protected var _application:IShellApplication;
		
		public function get application() : IShellApplication {
			return this._application;
		}
		
		public function set application(value:IShellApplication) : void {
			if ( this._application == null ) { this._application = value; }
		}
		
		protected var _module:DisplayObject;
		
		public function get module() : DisplayObject {
			return this._module;
		}
		
		protected var _url:String;
		
		public function get url() : String {
			return this._url;
		}
		
		public function set url(value:String) : void {
			if ( this._url == null ) { this._url = value; }
		}
		
		protected var _deferHide:Boolean = false;
		protected var _deferShow:Boolean = false;
		private var _moduleInfo:IModuleInfo;
		
		public function ModuleDelegateView(enforcer:ModuleDelegateViewEnforcer=null) : void { super(enforcer); }
		
		public static function getInstance() : ModuleDelegateView {
			if ( _instance == null ) {
				_instance = new ModuleDelegateView(new ModuleDelegateViewEnforcer());
			}
			
			return _instance;
		}
		
		override public function initialize() : void {
			super.initialize();
		}
		
		override public function draw() : void {}
		
		protected function loadModule() : void {
			this._moduleInfo = ModuleManager.getModule(this._url);
			this._moduleInfo.addEventListener(ModuleEvent.PROGRESS, moduleEventProgressHandler, false, 0, true);
			this._moduleInfo.addEventListener(ModuleEvent.READY, moduleEventReadyHandler, false, 0, true);
       		this._moduleInfo.addEventListener(ModuleEvent.ERROR, moduleEventErrorHandler, false, 0, true);
       		this._moduleInfo.load(ApplicationDomain.currentDomain);
		}
		
		override public function hide(targetView:ViewBase, targetState:String=null) : void {
			if ( this._module != null ) {
				this._module.alpha = 0;
				this._module.visible = Boolean(this._module.alpha);
			} else { //The module does not exist, defer the hide.
				this._deferHide = true;
			}
			
			this.alpha = 0;
			this.visible = Boolean(this.alpha);
		}
		
		override public function show(targetView:ViewBase) : void {
			if ( this._module != null ) { //The module has been loaded, show it.
				this._module.alpha = 1;
				this._module.visible = Boolean(this._module.alpha);
			} else { //The module does not exist, lazy load it.
				if ( this._deferShow == false ) {
					this._deferShow = true;
				
					loadModule();
				}
			}
			
			this.alpha = 1;
			this.visible = Boolean(this.alpha);
		}
		
		//The module binary has loaded, create the module object. 
		protected function moduleEventReadyHandler(event:ModuleEvent) : void {
			var moduleName:String = event.module.url.split("/")[event.module.url.split("/").length - 1];
        		moduleName = moduleName.split(".")[0];
        		moduleName = moduleName.substring(0, 1).toLowerCase() + moduleName.substring(1);
        	
        	this._module = DisplayObject(event.module.factory.create() as DisplayObject);
        	this._module.name = moduleName;
        	this._moduleInfo.removeEventListener(ModuleEvent.READY, moduleEventReadyHandler, false);
        	this._moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleEventErrorHandler, false);
        	this._module.addEventListener(OutboundEvent.OUTBOUND_EVENT, this._application.getOutboundEventHandler(), false, 0, true);
        	this._module.addEventListener(OutboundEvent.OUTBOUND_EVENT, moduleOutboundEventHandler, false, 0, true);
        	
        	addChild(this._module);
        	
        	if ( this._deferHide == true ) {
        		this._deferHide = false;
        		hide(this);
        	}
        	
        	if ( this._deferShow == true ) {
        		this._deferShow = false;
        		show(this);
        	}
        }
        
        protected function moduleEventProgressHandler(event:ModuleEvent) : void {
        	var bytesLoaded:Number = ModuleEvent(event as ModuleEvent).bytesLoaded;
        	var bytesTotal:Number = ModuleEvent(event as ModuleEvent).bytesTotal;
        }
        
       	protected function moduleEventErrorHandler(e:ModuleEvent) : void {}
		
		//Handle outbound events from the modules at the view level.
		protected function moduleOutboundEventHandler(event:OutboundEvent) : void {
			/* If you want to handle the NetStatusEvent disk write from 
			   LocalDataDelegate somewhere else, override your sublcass 
			   method and set the following properties on LocalDataDelegate:
			   LocalDataDelegate.callback = anotherMethod;
			   LocalDataDelegate.scope = anotherScope;
			   LocalDataDelegate.argumentsArray = [aProperty, "someString", etCeteraProperty]; */
			
			LocalDataDelegate.callback = initializeModule;
			LocalDataDelegate.scope = this;
			
			if ( event.creationComplete == true ) {
				if ( this._application.persistModelToDisk ) { //The module has been created, write the application model to disk.
					LocalDataDelegate.writeToDisk(); //Call back to initializeModule().
					SharedStateDelegate.writeToDisk();
				}
				
				initializeModule([]);
			}
		}
		
		private function initializeModule(argumentsArray:Array) : void {
			//Inject the module with the current application model.
			var navigationEvent:InboundEvent = new InboundEvent(InboundEvent.INBOUND_EVENT);
				navigationEvent.inboundNotificationVO = VOUtil.clone((this._application["shellModelVO"] as ShellModelVO), ShellModuleVO, true);
				
			this._module.dispatchEvent(navigationEvent);
		}
		
		public function DestroyModuleDelegateView() : void {
			if ( this._moduleInfo != null && this._moduleInfo.loaded == false ) {
				if ( this._moduleInfo.hasEventListener(ModuleEvent.PROGRESS) ) { this._moduleInfo.removeEventListener(ModuleEvent.PROGRESS, moduleEventProgressHandler, false); }
				if ( this._moduleInfo.hasEventListener(ModuleEvent.READY) ) { this._moduleInfo.removeEventListener(ModuleEvent.READY, moduleEventReadyHandler, false); }
       			if ( this._moduleInfo.hasEventListener(ModuleEvent.ERROR) ) { this._moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleEventErrorHandler, false); }
			}
			
			this._module.removeEventListener(OutboundEvent.OUTBOUND_EVENT, this._application.getOutboundEventHandler(), false);
        	this._module.removeEventListener(OutboundEvent.OUTBOUND_EVENT, moduleOutboundEventHandler, false);
			
			this._application = null;
			this._module = null;
			
			if ( this._moduleInfo != null ) {
				this._moduleInfo.release();
				this._moduleInfo = null;
			}
			
			this._url = "";
			delete this;
		}
	}
}